package com.hykc.auth.interceptor;

import com.hykc.auth.common.CookieUtils;
import com.aopuxun.common.auth.entity.Payload;
import com.aopuxun.common.auth.entity.UserInfo;
import com.aopuxun.common.auth.utils.JwtUtils;
import com.aopuxun.common.threadlocals.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = CookieUtils.getCookieValue(request, "DD_TOKEN");
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            Integer userId = payload.getUserInfo().getId();
            UserHolder.set(userId);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
